package com.example.ignite;

import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.Ignition;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;

import java.util.Arrays;
import java.util.List;

public class IgniteUserSample {
    public static void main(String[] args) {
        // 配置 Ignite
        IgniteConfiguration cfg = new IgniteConfiguration();
        
        // 配置发现机制
        TcpDiscoverySpi discoverySpi = new TcpDiscoverySpi();
        TcpDiscoveryVmIpFinder ipFinder = new TcpDiscoveryVmIpFinder();
        ipFinder.setAddresses(Arrays.asList("127.0.0.1:47500..47509"));
        discoverySpi.setIpFinder(ipFinder);
        cfg.setDiscoverySpi(discoverySpi);

        // 启动 Ignite
        try (Ignite ignite = Ignition.start(cfg)) {
            System.out.println("Ignite 节点已启动");

            // 获取或创建缓存
            IgniteCache<Long, User> userCache = ignite.getOrCreateCache("users");

            // 创建用户对象
            User user = new User();
            user.setId(1L);
            user.setUsername("test_user");
            user.setEmail("test@example.com");
            user.setFirstName("Test");
            user.setLastName("User");
            user.setAge(30);
            user.setStatus("ACTIVE");
            user.setLoginCount(0);

            // 将用户对象存入缓存
            userCache.put(user.getId(), user);
            System.out.println("用户数据已写入缓存");

            // 从缓存中读取用户数据
            User cachedUser = userCache.get(user.getId());
            System.out.println("从缓存中读取的用户名: " + cachedUser.getUsername());

            // 使用 SQL 查询
            String sql = "SELECT COUNT(*) FROM User";
            List<List<?>> result = userCache.query(new org.apache.ignite.cache.query.SqlFieldsQuery(sql))
                    .getAll();
            if (!result.isEmpty() && !result.get(0).isEmpty()) {
                Object count = result.get(0).get(0);
                System.out.println("缓存中的用户数量: " + count);
            }
        }
    }
} 